<?php

namespace Database\Seeders;

// use App\Models\Permission;
use App\Models\Role;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // 定义角色
        $arrayOfRoleNames = ['admin', 'distributor', 'member'];
        $roles = collect($arrayOfRoleNames)->map(fn ($role) => ['name' => $role, 'guard_name' => 'user'])
            ->toArray();

        // 批量插入角色
        Role::insert($roles);

        /**
         * 角色权限范围
         *
         * authorization 平台授权
         * component 第三方操作
         * user 用户权限
         */
        $permissionsByRole = [
            // 管理
            'admin' => [
                'restore authorizations',
                'force delete authorizations',
                'restore components',
                'force delete components',
            ],
            // 分销
            'distributor' => [
                'create a authorization',
                'update a authorization',
                'delete a authorization'
            ],
            // 会员
            'member' => [
                'view all authorizations',
                'view a authorization'
            ]
        ];

        // 生成角色
        $insertPermissions = fn ($role) => collect($permissionsByRole[$role])
            ->map(fn ($name) => DB::table('permissions')->insertGetId(['name' => $name, 'guard_name' => 'user']))
            ->toArray();

        $permissionIdsByRole = [
            // 管理
            'admin' => $insertPermissions('admin'),
            // 分销
            'distributor' => $insertPermissions('distributor'),
            // 会员
            'member' => $insertPermissions('member')
        ];

        foreach ($permissionIdsByRole as $role => $permissionIds) {
            // 角色
            $role = Role::whereName($role, 'user')->first();
            // 角色、权限进行绑定
            DB::table('role_has_permissions')
                ->insert(
                    collect($permissionIds)->map(fn ($id) => [
                        'role_id' => $role->id,
                        'permission_id' => $id
                    ])->toArray()
                );
        }
    }
}
